const express = require("express");
const router = express.Router();
const axios = require("axios");

const a = {
  appid: "56436784",
  appsecret: "Y1ps0xuK"
};
// 我的
const b = {
  appid: "67914774",
  appsecret: "uLi3tuAy"
};

const config = {
  g: "http://gfeljm.tianqiapi.com",
  base: "http://v1.yiketianqi.com",
  ...a
};

// 获取天气 day 一天 week 一周
router.get("/", async function (req, res) {
  // week
  const { type } = req.query;
  // const clientIp = req.ip;
  // const clientIp = "119.113.117.217";
  // unescape=1 返回中文
  const ip =
    req.headers["x-forwarded-for"] || req.ip || req.socket.remoteAddress;
  axios
    .get(`${config.base}/free/${type || "day"}`, {
      params: {
        unescape: 1,
        appid: config.appid,
        appsecret: config.appsecret,
        ip: ip
      }
    })
    .then((resp) => {
      res.send({
        code: 200,
        data: resp.data,
        message: "success"
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        data: null,
        message: err
      });
    });
});

// 获取一个月天气
router.get("/month", async function (req, res) {
  const ip =
    req.headers["x-forwarded-for"] || req.ip || req.socket.remoteAddress;
  axios
    .get(`${config.base}/free/month`, {
      params: {
        unescape: 1,
        appid: config.appid,
        appsecret: config.appsecret,
        ip: ip
      }
    })
    .then((resp) => {
      res.send({
        code: 200,
        data: resp.data,
        message: "success"
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        data: null,
        message: err
      });
    });
});

// 实况24小时
router.get("/live", async (req, res) => {
  // const clientIp = req.ip;
  // const clientIp = "119.113.117.217";
  const ip =
    req.headers["x-forwarded-for"] || req.ip || req.socket.remoteAddress;

  axios
    .get(`${config.g}/free/v2030`, {
      params: {
        unescape: 1,
        appid: config.appid,
        appsecret: config.appsecret,
        ip: ip,
        aqi: 1,
        hours: 1
      }
    })
    .then((resp) => {
      if (resp.data.errcode) {
        res.send({
          code: resp.data.errcode,
          data: resp.data,
          message: resp.data.errmsg
        });
        return;
      }
      res.send({
        code: 200,
        data: resp.data,
        message: "success"
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        data: null,
        message: String(err)
      });
    });
});

module.exports = router;
